package com.yunshipei.ui.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kyleduo.switchbutton.SwitchButton;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.inter.ModifyPasCallBack;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.YspEvent;
import com.yunshipei.model.YspEvent.MessageCountClearEvent;
import com.yunshipei.ui.activity.FontSizeSettingsActivity;
import com.yunshipei.ui.activity.MessageAlertActivity;
import com.yunshipei.ui.activity.ModifyPasswordActivity;
import com.yunshipei.ui.activity.SSOActivity;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ToastUtils;

import java.util.List;

import butterknife.Bind;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIMClientWrapper;
import io.rong.imlib.model.Conversation;

public class SettingsFragment extends BaseBodyFragment implements View.OnClickListener {

    @Bind(R.id.ll_settings_container)
    protected LinearLayout mContainer;
    @Bind(R.id.sb_auto_update)
    protected SwitchButton mSwitchButton;
    @Bind(R.id.tv_title)
    protected TextView tvTitle;

    private Context mContext;
    private SharedPreferences mPreferences;

    public static Fragment newInstance(MainExtraBean mainExtraBean) {
        SettingsFragment settingsFragment = new SettingsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_CUSTOMER_MAIN_DATA, mainExtraBean);
        settingsFragment.setArguments(bundle);
        return settingsFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
    }

    @Override
    public int viewLayout() {
        return R.layout.fragment_settings;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        boolean isPad = isPad();
        tvTitle.setText(getString(R.string.setting));
        tvTitle.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        tvTitle.setVisibility(isPad ? View.VISIBLE : View.GONE);
        mSwitchButton.setCheckedImmediately(mPreferences.getBoolean(Globals.SP_SPLASH_CHECK_UPDATE, true));
        mSwitchButton.setBackColor(BaseUtil.getCurrentSwitchButtonColor(getActivity()));
        mSwitchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mPreferences.edit().putBoolean(Globals.SP_SPLASH_CHECK_UPDATE, isChecked).apply();
            }
        });
        Items[] items = Items.values();
        for (int i = 0; i < items.length; i++) {
            View childView = mContainer.getChildAt(i + 1);
            childView.setTag(items[i]);
            childView.setOnClickListener(this);
            TextView textView = (TextView) childView.findViewById(R.id.tv_item_content);
            ImageView imageView = (ImageView) childView.findViewById(R.id.iv_right_indicator);
            textView.setText(items[i].name);
            imageView.setVisibility(items[i].visibility);
            if (isPad) {
                switch (items[i]) {
                    case MESSAGE_ALERT:
                    case CLEAR_MESSAGE:
                        childView.setVisibility(View.GONE);
                        break;
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        Items items = (Items) v.getTag();
        switch (items) {
            case MESSAGE_ALERT:
                startActivity(new Intent(getActivity(), MessageAlertActivity.class));
                break;
            case SSO_LOGIN:
                if (isPad()) {
                    EventBus.getDefault().post(new YspEvent.SWA());
                } else {
                    startActivity(new Intent(new SSOActivity.SSOActivityIntentBuilder(getActivity()).setMainData(mMainExtraBean).getIntent()));
                }
                break;
            case CLEAR_CACHE:
                DialogHelper.getAlertDialogCancelable(getActivity(), "将清空Enterplorer本地缓存数据？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        final WaitDialog waitDialog = new WaitDialog(getActivity());
                        waitDialog.setMessage("正在删除缓存...");
                        Flowable.create(new FlowableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(FlowableEmitter<Boolean> e) throws Exception {
                                String path = Environment.getExternalStorageDirectory() + "/yunshipei";
                                String cachePath = getActivity().getCacheDir().getPath();
                                BaseUtil.deletePathReal(path);
                                BaseUtil.deletePathReal(cachePath);
                                e.onNext(true);
                            }
                        }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(Boolean aBoolean) throws Exception {
                                        waitDialog.dismiss();
                                        ToastUtils.showToast("清空缓存成功");
                                    }
                                });
                    }
                }).show();
                break;
            case CLEAR_MESSAGE:
                DialogHelper.getAlertDialogCancelable(getActivity(), "将清空所有个人和群的聊天记录？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null || RongIM.getInstance().getRongIMClient().getConversationList() == null) {
                            ToastUtils.showToast("没有聊天会话记录");
                            return;
                        }
                        List<Conversation> conversations = RongIM.getInstance().getRongIMClient().getConversationList();
                        RongIMClientWrapper wrapper = RongIM.getInstance().getRongIMClient();
                        for (Conversation conversation : conversations) {
                            wrapper.clearMessages(conversation.getConversationType(), conversation.getTargetId());
                        }
                        EventBus.getDefault().post(new MessageCountClearEvent());
                        ToastUtils.showToast("已清空所有聊天记录");
                    }
                }).show();
                break;
            case MODIFY_PASSWORD:
                DialogHelper.checkPasswordDialog(mContext, new ModifyPasCallBack() {
                    @Override
                    public void oldPasCheckFinished() {
                        //验证成功，进入密码修改界面
                        if (isPad()) {
                            EventBus.getDefault().post(new YspEvent.ModifyPwd());
                        } else {
                            startActivity(new ModifyPasswordActivity.ModifyPwdActivityIntentBuilder(mContext).setMainData(mMainExtraBean).getIntent());
                        }
                    }
                });
                break;
            case FONT_SIZE_ZOOM:
                if (isPad()) {
                    EventBus.getDefault().post(new YspEvent.FontSizeSetting());
                } else {
                    startActivity(new FontSizeSettingsActivity.FontSizeSettingsIntentBuilder(mContext).getIntent());
                }
                break;
            case AUTO_UPDATE:
                mSwitchButton.performClick();
                break;
        }
    }

    private enum Items {
        MESSAGE_ALERT("新消息提醒", View.VISIBLE),
        SSO_LOGIN("密码管家", View.VISIBLE),
        FONT_SIZE_ZOOM("字体大小", View.VISIBLE),
        CLEAR_CACHE("清空缓存", View.GONE),
        CLEAR_MESSAGE("清空聊天记录", View.GONE),
        MODIFY_PASSWORD("修改密码", View.GONE),
        AUTO_UPDATE("自动升级", View.GONE);

        private String name;
        private int visibility;

        Items(String name, int visibility) {
            this.name = name;
            this.visibility = visibility;
        }
    }
}
